#addin "Cake.Npm"
#tool "nuget:?package=OctopusTools"

var target        = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
var releaseNumber = Argument("releaseNumber", "");

var solution                 = "ComprehensiveESGResearch.UI.sln";
var uiFolder                 = "./Service/";
var buildDir                 = "./Service/bin/" + configuration;
var nugetOutputDir           = "./artifacts";
var octopusDeployProjectName = "ComprehensiveESGResearch.UI";
var octopusDeployServer      = "http://10.120.120.11:8082";
var octopusDeployApiKey      = "API-MBFQMNHSNQE2OQHPSBIQH3MKEY";

EnsureDirectoryExists(nugetOutputDir);

Task("Clean")
  .Does(() => CleanDirectories(new[] { buildDir, nugetOutputDir }));

Task("NpmInstall")
  .Does(() => Npm.FromPath(uiFolder).Install());

Task("Webpack")
  .Does(() => Npm.FromPath(uiFolder).RunScript("webpack-prod"));

Task("CopyUI")
  .Does(() => CopyDirectory(uiFolder + "/dist", buildDir + "/app"));

Task("NuGetRestore")
  .Does(() => NuGetRestore(solution));

Task("Build")
  .IsDependentOn("Clean")
  .IsDependentOn("NpmInstall")
  .IsDependentOn("Webpack")
  .IsDependentOn("CopyUI")
  .IsDependentOn("NuGetRestore")
  .Does(() => MSBuild(solution, new MSBuildSettings { Configuration = configuration }));

Task("NuGetPack")
  .WithCriteria(HasArgument("releaseNumber"))
  .Does(() => NuGetPack("./Service.nuspec", new NuGetPackSettings {
    Version = releaseNumber,
    BasePath = buildDir,
    OutputDirectory = nugetOutputDir,
    ArgumentCustomization = args => args.Append("-Prop Configuration=" + configuration),
  }));

Task("NuGetPush")
  .WithCriteria(HasArgument("releaseNumber"))
  .Does(() => GetFiles(nugetOutputDir + "/*.nupkg").ToList()
    .ForEach(package => NuGetPush(package, new NuGetPushSettings {
      Source = octopusDeployServer + "/nuget/packages",
      ApiKey = octopusDeployApiKey,
    })));

Task("OctoCreateRelease")
  .WithCriteria(HasArgument("releaseNumber"))
  .Does(() => OctoCreateRelease(octopusDeployProjectName, new CreateReleaseSettings {
    Server = octopusDeployServer,
    ApiKey = octopusDeployApiKey,
    ReleaseNumber = releaseNumber,
  }));

Task("Default")
  .IsDependentOn("Build");
  //.IsDependentOn("NuGetPack");

Task("PrepareDeploy")
  .IsDependentOn("Default");
  //.IsDependentOn("NuGetPush")
  //.IsDependentOn("OctoCreateRelease");

RunTarget(target);
